﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace AlphaSolutionsGP
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();

            // these are help tips when f1 is pressed and focus is on one of the text inputs
            this.hlpLoginHelp = new System.Windows.Forms.HelpProvider();
            this.hlpLoginHelp.SetShowHelp(this.txtUserId, true);
            this.hlpLoginHelp.SetHelpString(this.txtUserId, "Enter your User ID in this text box.");
            this.hlpLoginHelp.SetShowHelp(this.txtPassword, true);
            this.hlpLoginHelp.SetHelpString(this.txtPassword, "Enter your password in this text box.");
            this.hlpLoginHelp.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.TableOfContents);
            this.hlpLoginHelp.SetShowHelp(this, true);
            

        }

        /* simple function to show the message box
         * there are a number of buttons on this screen that fire this function
         * including the help ? icon and the help button in the toolbar menu
         */
        private void showHelp()
        {
            MessageBox.Show("To login to your area of the system- type your student number or username into the username box and " +
            "your password into the password box. Simply click login and if your credentials are correct you will be logged in.",
            "Login Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        // what happens when the "Forget Password" link is clicked
        private void lblForget_Click(object sender, EventArgs e)
        {
            MessageBox.Show("If you have forgotten or lost your password please contact an administrator for your course.","Forgot Password",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        //  the message box to appear when the help "?" is clicked
        private void btnHelp_Click(object sender, EventArgs e)
        {
            showHelp();
        }

        /* this opens the frmAbout form which is a small splash window to show information
         * about the product
         */
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAbout f = new frmAbout();
            f.Show();
        }

        //  the message box to appear when the help button in the toolbar menu is clicked
        private void viewHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showHelp();
        }

        /* this opens the frmAbout form which is a small splash window to show information
         * about the product
         */
        private void btnAbout_Click(object sender, EventArgs e)
        {
            frmTimetableView f = new frmTimetableView();
            f.Show();
        }

        /* these functions will detect when the user is ready to login and
         * the validation function will be executed
         */ 
        private void btnLogin_Click(object sender, EventArgs e) { loginValidation(); }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        { if (e.KeyCode == Keys.Enter) loginValidation(); }


        /* login validation procedure
         */
        private void loginValidation()
        {
            Cursor.Current = Cursors.WaitCursor;
            //validation of login form
            //validation to ensure inputs are not empty
            if (txtUserId.Text == "" || !validUsername(txtUserId.Text))
            {
                MessageBox.Show("Login error, username field", "Login Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {

                //username is now valid and in the database
                if (!validPass(txtUserId.Text, txtPassword.Text))
                {
                    MessageBox.Show("Login error, password does not match", "Login Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {

                    // if execution gets to here, login credentials are correct and proceed with login
                    frmWoodlandsSystemMain f = new frmWoodlandsSystemMain();
                    f.Show();
                    this.Hide();
                }
            }
            Cursor.Current = Cursors.Arrow;

        }

        /* this function will return true if the username is a valid username from the database
         */
        private bool validUsername(String usr)
        {
            //search the database of user names and return false if not valid
            bool flag = false;
            
            //dummy validation just to prove function works
            //if (usr == "ross")
            //{
            //    flag = true;
            //}


            /*this is the username validation for the student 
            (retreive the username entered and compare it against the existing ones)*/

            MySqlConnection connection = new MySqlConnection("server=194.81.104.22;" + "User Id=alpha;" + "database=alpha_db;" + "password=bravo;");
            try
            {
                connection.Open();
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Connection failed");
            }
            try
            {
                MySqlCommand cmd = connection.CreateCommand();
                string studentID, staffID; //variables for storing the reader value

                bool isStudent = false;
                bool isStaff = false;

                //get thevalue from the text box id
                string idValue = txtUserId.Text;

                if (idValue.StartsWith("2"))
                {
                    //query STUDENT table
                    cmd.CommandText = "SELECT student_ID FROM STUDENT";
                    MySqlDataAdapter studentIdQuery = new MySqlDataAdapter(cmd);
                    isStudent = true;
                }
                else
                {
                    if (idValue.StartsWith("9"))
                    {
                        // query STAFF table
                        cmd.CommandText = "SELECT staff_ID FROM STAFF";
                        MySqlDataAdapter staffIdQuery = new MySqlDataAdapter(cmd);
                        isStaff = true;
                    }
                }
                var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);


                while (reader.Read() & !flag)
                {
                    if (isStudent)
                    {
                        studentID = (string)reader["student_ID"];//store the reader value
                        if (txtUserId.Text.Equals(studentID))
                        {
                            flag = true;
                        }
                    }
                    else
                    {
                        if (isStaff)
                        {
                            staffID = (string)reader["staff_ID"];
                            if (txtUserId.Text.Equals(staffID))
                            {
                                flag = true;
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to process due to the following error:\n\n" + ex.ToString());
            }
            finally
            {
                connection.Close();

            }

            return flag;
        }

        /* this function recieves the username and password passed from the login form and
         * processes the password against the username provided
         */
        private bool validPass(String usr, String pass)
        {
            bool flag = false;
            
            //store correct password to validate against
            //string correctPass = "pass";

            //if (pass == correctPass)
            //{
            //    flag = true;
            //}


            /*this is the username validation for the student 
            (retreive the username entered and compare it against the existing ones)*/

            MySqlConnection connection = new MySqlConnection("server=194.81.104.22;" + "User Id=alpha;" + "database=alpha_db;" + "password=bravo;");
            try
            {
                connection.Open();
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("Connection failed");
            }
            try
            {
                MySqlCommand cmd = connection.CreateCommand();
                string pwd; //store the reader value

                bool isStudent = false; //the id entered is a student id
                bool isStaff = false; //the id entered is a staff id

                //get thevalue from the text box password
                string pswValue = txtPassword.Text;
                //get thevalue from the text box id
                string idValue = txtUserId.Text;

                if (idValue.StartsWith("2"))
                {
                    //query STUDENT table
                    cmd.CommandText = "SELECT password FROM STUDENT";
                    MySqlDataAdapter studentIdQuery = new MySqlDataAdapter(cmd);
                    isStudent = true;
                }
                else
                {
                    if (idValue.StartsWith("9"))
                    {
                        // query STAFF table
                        cmd.CommandText = "SELECT password FROM STAFF";
                        MySqlDataAdapter staffIdQuery = new MySqlDataAdapter(cmd);
                        isStaff = true;
                    }
                }
                var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);


                while (reader.Read() & !flag)
                {
                    pwd = (string)reader["password"];
                    if (txtPassword.Text.Equals(pwd))
                    {
                        flag = true;
                    }
                }

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to process due to the following error:\n\n" + ex.ToString());
            }
            finally
            {
                connection.Close();

            }


            return flag;
        }

        private void frmLogin_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            frmAbout f = new frmAbout();
            f.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UnitTesting f = new UnitTesting();
            f.Show();
        }
        
    }
}
